<script setup lang="ts">
import { ref, unref } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { ElTree, ElButton, ElLoading, ElMessageBox, ElInput, ElTabs, ElTabPane } from 'element-plus'
// import { useIcon } from '@/hooks/web/useIcon'
import { changeRoute } from '@/utils/lee'
import { ucMenuListApi, ucMenuAddApi, ucMenuEditApi, ucMenuDelApi } from '@/api/uc/menu'
import { ucAppListApi } from '@/api/uc/app'
import { useI18n } from '@/hooks/web/useI18n'
import { Dialog } from '@/components/Dialog'
import Edit from './components/Edit.vue'
import { useCache } from '@/hooks/web/useCache'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const { wsCache } = useCache()
const permissionStore = usePermissionStore()

const { addRoute } = useRouter()
const { t } = useI18n()
// const loading = ref(false)
const loading = ref({
  tree: false,
  save: false
})
const iconSize = 16
const iconColor = '#999'

const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')
const formData = ref<any>({})

const menuData = ref<any>([])
const defaultProps = {
  children: 'children',
  label: 'menu_name'
}
let tabValue = ref('2')
const appData = ref<any>([])
const getUcAppListApi = async () => {
  const res = await ucAppListApi({})
    .catch(() => {})
    .finally(() => {})
  if (res) {
    console.log('getUcAppListApi', res.data)
    appData.value = res.data
    tabValue.value = res.data[0].app_id
  }
}

getUcAppListApi()

const deleteApi = async (id) => {
  const res = await ucMenuDelApi({ menu_id: id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    // menuData.value = res.data
    getList({ app_id: tabValue.value })
  }
}
var routers: any = []
const routersString = ref('')

const action = (type: string, data?: any) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = t('编辑菜单')
      formData.value = data
      if (formData.value.disp_order != null && typeof formData.value.disp_order === 'string') {
        formData.value.disp_order = Number(formData.value.disp_order)
      }
      dialogVisible.value = true
      break
    case 'addChildren':
      dialogTitle.value = t('新增下级菜单')
      formData.value = {
        parent_id: data.menu_id,
        disp_order: 0
      }
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = t('新增菜单')
      formData.value = {
        parent_id: '0',
        disp_order: 0
      }
      dialogVisible.value = true
      break
    case 'delete':
      ElMessageBox.confirm('确定要删除这个菜单？', '删除菜单', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteApi(data.menu_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'updateRoute':
      dialogTitle.value = t('更新路由')
      routers = changeRoute(menuData.value)
      // console.log('routers', JSON.stringify(routers))
      routersString.value = JSON.stringify(routers)
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}

const getList = async (data) => {
  // const loadingInstance = ElLoading.service(options)
  const loadingMain = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await ucMenuListApi(data)
    .catch(() => {})
    .finally(() => {
      setTimeout(() => {
        loadingMain.close()
      }, 500)
    })
  if (res) {
    menuData.value = res.data
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()

// const changeRoute = (data) => {
//   // console.log('changeRoute1', data)
//   let newData: any = []
//   data.forEach((item) => {
//     // console.log('item', item)
//     let newItem: any = {
//       path: item.path,
//       component: item.component,

//       name: item.menu_code,
//       meta: {
//         title: item.menu_name,
//         hidden: item.hidden == '1' ? true : false,
//         alwaysShow: item.alwaysShow == '1' ? true : false,
//         noCache: item.noCache == '1' ? true : false,
//         breadcrumb: item.breadcrumb == '1' ? true : false,
//         affix: item.affix == '1' ? true : false,
//         noTagsView: item.noTagsView == '1' ? true : false,
//         canTo: item.canTo == '1' ? true : false
//       }
//     }
//     if (item.redirect != null && item.redirect != '') {
//       newItem.redirect = item.redirect
//     }
//     if (item.icon != null && item.icon != '') {
//       newItem.meta.icon = item.icon
//     }
//     if (item.activeMenu != null && item.activeMenu != '') {
//       newItem.meta.activeMenu = item.activeMenu
//     }
//     if (item.followAuth != null && item.followAuth != '') {
//       newItem.meta.followAuth = item.followAuth
//     }

//     if (item.children != null && item.children != '') {
//       newItem.children = changeRoute(item.children)
//     }
//     newData.push(newItem)
//   })
//   return newData
// }

const save = async (type: string) => {
  let edit
  switch (type) {
    case 'edit':
      edit = unref(editRef)
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          // 点击后先让按钮loading
          loading.value.save = true
          const newData: any = await edit?.getFormData()
          newData.parent_id = newData.parent_id ? newData.parent_id : 0
          if (newData.value != null) {
            newData.menu_id = newData.value
          }
          if (newData.label != null) {
            newData.menu_name = newData.label
          }
          const data = { ...edit.oldFormData, ...newData }
          const res = await ucMenuEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value.save = false
            })
          if (res) {
            dialogVisible.value = false
            getList({ app_id: tabValue.value })
          }
        }
      })
      break
    case 'addChildren':
    case 'add':
      edit = unref(editRef)
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          // 点击后先让按钮loading
          loading.value.save = true
          const newData: any = await edit?.getFormData()
          newData.app_id = tabValue.value
          const data = { ...edit.oldFormData, ...newData }
          console.log('data', data)
          const addRes = await ucMenuAddApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value.save = false
            })
          if (addRes) {
            dialogVisible.value = false
            getList({ app_id: tabValue.value })
          }
        }
      })
      break
    case 'updateRoute':
      if (tabValue.value == '2') {
        // 点击后先让按钮loading
        loading.value.save = true
        wsCache.set('roleRouters', routers)
        await permissionStore.generateRoutes('admin', routers).catch(() => {})
        permissionStore.getAddRouters.forEach((route) => {
          addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
        })
        permissionStore.setIsAddRouters(true)
      } else {
        alert('系统管理才能更新路由')
      }
      loading.value.save = false
      dialogVisible.value = false
      break
    default:
      console.log('未知类型')
  }
}

//初始化
getList({ app_id: tabValue.value })
console.log(tabValue.value, 'vuauejijfeje')
const handleChange = (name) => {
  getList({ app_id: name })
}
</script>

<template>
  <ContentWrap>
    <ElTabs v-model="tabValue" type="card" class="demo-tabs" @tab-change="handleChange">
      <ElTabPane
        :label="item.app_name"
        :name="item.app_id"
        v-for="(item, index) in appData"
        :key="index"
      />
    </ElTabs>

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">{{ t('exampleDemo.add') }}</ElButton>
      <ElButton type="primary" @click="action('updateRoute')">更新路由</ElButton>
    </div>

    <div class="custom-tree-container">
      <el-tree
        :data="menuData"
        :props="defaultProps"
        node-key="menu_id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node }">
          <span class="custom-tree-node">
            <span>{{ node.data.menu_name }}</span>
            <span>
              <a @click="action('edit', node.data)">
                <Icon
                  icon="el:edit"
                  title="编辑"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <a @click="action('addChildren', node.data)">
                <Icon
                  icon="carbon:add-filled"
                  title="创建下级"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <a @click="action('delete', node.data)">
                <Icon
                  icon="fluent:delete-20-filled"
                  title="删除"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
            </span>
          </span>
        </template>
      </el-tree>
    </div>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add' || actionType == 'addChildren'"
      ref="editRef"
      :formData="formData"
      :meunData="menuData"
    />
    <ElInput
      v-if="actionType == 'updateRoute'"
      v-model="routersString"
      :rows="20"
      placeholder="Please input"
      type="textarea"
    />
    <template #footer>
      <ElButton type="primary" :loading="loading.save" @click="save(actionType)">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  a {
    padding: 0 3px;

    i {
      margin-top: 5px;
    }
  }
}
</style>
